package njci.softerware.com.myexpress2017.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.DrawableRes;
import android.support.v4.app.FragmentTabHost;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.github.mikephil.charting.utils.Utils;
import com.google.gson.Gson;

import java.io.IOException;

import butterknife.Bind;
import butterknife.ButterKnife;
import njci.softerware.com.myexpress2017.R;
import njci.softerware.com.myexpress2017.chart.PieChartActivity;
import njci.softerware.com.myexpress2017.fragement.HomeFragment;
import njci.softerware.com.myexpress2017.fragement.KuAidi;
import njci.softerware.com.myexpress2017.fragement.MIneInfoFragment;
import njci.softerware.com.myexpress2017.http.HttpClient;
import njci.softerware.com.myexpress2017.http.HttpResponseHandler;
import njci.softerware.com.myexpress2017.serviceObj.PackageInfo;
import njci.softerware.com.myexpress2017.serviceObj.dao.SharedPreferences;
import okhttp3.FormBody;
import okhttp3.Request;

public class MainActivity extends AppCompatActivity {


    RadioGroup main_group;

    private long mExitTime;
    private SearchView snQuery;
    //banner相关配置
    String[] arr_data = {"1"};
    private PackageInfo p;
    // 图片
    @DrawableRes
    private int mImages[] = {
            R.drawable.view_tab_dingdan,
            R.drawable.view_tab_mineinfo,
            R.drawable.view_tab_indicator,
    };
    private Class fragmentArray[] = {HomeFragment.class, KuAidi.class, MIneInfoFragment.class};

    @Bind(android.R.id.tabhost)
    FragmentTabHost mTabHost;
    private String mFragmentTags[] = {
            "首页",
            "订单",
            "我的",
    };
    Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setLogo(R.drawable.tab_contest_light);
        setSupportActionBar(toolbar);

        ButterKnife.bind(this);
        initWiget();
        initSearchView();
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String isToast = bundle.getString("showToast");
            if (isToast != null && isToast.equals("1")) {
                String result = bundle.getString("result");
                Toast.makeText(this, result, Toast.LENGTH_LONG).show();
                bundle = null;
            } else if (isToast != null && isToast.equals("2")) {
                bundle = null;
                Toast.makeText(this, "服务器连接失败", Toast.LENGTH_LONG).show();
            }
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Object mHelperUtils;
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();

            } else {
                initSH();
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void initSH() {
        SharedPreferences sh = SharedPreferences.getInstance();
        if (sh.getInt("recevie_count", 0) != 0) {
            sh.remove("recevie_count");
        }
        if (sh.getInt("dis_count", 0) != 0) {
            sh.remove("dis_count");
        }
        if (sh.getInt("sign_count", 0) != 0) {
            sh.remove("sign_count");
        }
        if (sh.getLong("tmpTime",0) != 0) {
        sh.remove("tmpTime");}
    }

    //初始化tabHost
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void initWiget() {
        mTabHost.setup(MainActivity.this, getSupportFragmentManager(), android.R.id.tabcontent);
        mTabHost.getTabWidget().setDividerDrawable(null); // 去掉分割线
        for (int i = 0; i < mFragmentTags.length; i++) {
            // Tab按钮添加文字和图片
            TabHost.TabSpec tabSpec = mTabHost.newTabSpec(mFragmentTags[i]).setIndicator(getImageView(i));
            // 添加Fragment
            mTabHost.addTab(tabSpec, fragmentArray[i], null);
        }
        mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
            @Override
            public void onTabChanged(String tabId) {
                switch (tabId) {
                    case "首页":
                        if (toolbar.getVisibility() == View.GONE) {
                            toolbar.setVisibility(View.VISIBLE);
                        }
                        break;
                    case "订单":
                        if (toolbar.getVisibility() == View.GONE) {
                            toolbar.setVisibility(View.VISIBLE);
                        }
                        break;
                    case "我的":
                        if (toolbar.getVisibility() == View.VISIBLE) {
                            toolbar.setVisibility(View.GONE);
                        }
                        break;
                    default:
                        break;
                }
            }
        });

    }


    //初始化toolbarhe
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void initSearchView() {
        snQuery = (SearchView) findViewById(R.id.snQuery);
        snQuery.setIconifiedByDefault(false);
        snQuery.setSubmitButtonEnabled(true);
        snQuery.setQueryHint("查询快递");
        snQuery.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                querySN(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
    }


    public void querySN(String sn) {
        String url = "http://myexpress2016.carp.mopaasapp.com/getBySN";
        FormBody formBody = new FormBody.Builder().add("sn", sn)
                .build();
        HttpClient.post(url, formBody, new HttpResponseHandler() {
            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                try {
                    if (content.contains("sn")) {
                        Gson g = new Gson();
                        Message m = new Message();
                        p = g.fromJson(content, PackageInfo.class);
                        Intent intent = new Intent(MainActivity.this, DetailSn.class);
                        Bundle bundle = new Bundle();
                        bundle.putParcelable("PackageInfo", p);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    } else {
                        Toast.makeText(MainActivity.this, "订单不存在", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void sendFailureMessage(Request request, IOException e) {
                Toast.makeText(MainActivity.this, "服务器连接失败", Toast.LENGTH_SHORT).show();
                super.sendFailureMessage(request, e);
            }
        });
    }

    // 获得图片资源
    private View getImageView(int index) {
        @SuppressLint("InflateParams")
        View view = getLayoutInflater().inflate(R.layout.tabwiget_backgroud, null);
        ImageView imageView = (ImageView) view.findViewById(R.id.tab_iv_image);
        TextView textView = (TextView) view.findViewById(R.id.wiget_text);
        imageView.setImageResource(mImages[index]);
        textView.setText(mFragmentTags[index]);
        return view;
    }


}

